<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="店铺id" prop="shopId">
                <el-input v-model.trim="queryParams.shopId" placeholder="请输入店铺id" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="统计周期" prop="dataDate">
                <el-date-picker clearable v-model="queryParams.dataDate" type="date" value-format="yyyy-MM-dd"
                    placeholder="请选择统计周期">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                <el-button :icon="!isOpen ? 'el-icon-arrow-down' : 'el-icon-arrow-up'" size="mini"
                    @click="shouqi">展开/收起</el-button>
            </el-form-item>

            <div v-if="isOpen">
                <el-form-item label="商品名称" prop="productName">
                    <el-input v-model.trim="queryParams.productName" placeholder="请输入商品名称" clearable
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="商品编码" prop="productId">
                    <el-input v-model.trim="queryParams.productId" placeholder="请输入商品编码" clearable
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="品类" prop="category">
                    <el-input v-model.trim="queryParams.category" placeholder="请输入品类" clearable
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="自卖/合作" prop="selfSellingOrCooperation">
                    <el-input v-model.trim="queryParams.selfSellingOrCooperation" placeholder="请输入自卖/合作" clearable
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="成交金额" prop="totalAmount">
                    <el-input v-model.trim="queryParams.totalAmount" placeholder="请输入成交金额" clearable
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="成交订单数" prop="totalOrderCount">
                    <el-input v-model.trim="queryParams.totalOrderCount" placeholder="请输入成交订单数" clearable
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="成交人数" prop="transactionUsers">
                    <el-input v-model.trim="queryParams.transactionUsers" placeholder="请输入成交人数" clearable
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="商品曝光人数" prop="exposedUsersCount">
                    <el-input v-model.trim="queryParams.exposedUsersCount" placeholder="请输入商品曝光人数" clearable
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="商品点击人数" prop="productClickPeopleCount">
                    <el-input v-model.trim="queryParams.productClickPeopleCount" placeholder="请输入商品点击人数" clearable
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="曝光点击率" prop="exposureClickRateCount">
                    <el-input v-model.trim="queryParams.exposureClickRateCount" placeholder="请输入曝光点击率" clearable
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="点击支付率" prop="clickPaymentRateCount">
                    <el-input v-model.trim="queryParams.clickPaymentRateCount" placeholder="请输入点击支付率" clearable
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="上架时间" prop="uploadTime">
                    <el-date-picker clearable v-model="queryParams.uploadTime" type="date" value-format="yyyy-MM-dd"
                        placeholder="请选择上架时间">
                    </el-date-picker>
                </el-form-item>
            </div>
            <!-- <el-form-item label="逻辑删除" prop="isDelete">
                <el-input v-model.trim="queryParams.isDelete" placeholder="请输入逻辑删除" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item> -->
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['productStructure:BiDyMarketingPro:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['productStructure:BiDyMarketingPro:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                    v-hasPermi="['productStructure:BiDyMarketingPro:remove']">删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['productStructure:BiDyMarketingPro:export']">导出</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button size="mini" plain icon="el-icon-upload" @click="daoru">导入</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="BiDyMarketingProList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="id" align="center" prop="id" />
            <el-table-column label="店铺id" align="center" prop="shopId" />
            <el-table-column label="统计周期" align="center" prop="dataDate" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.dataDate, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="true" label="商品名称" align="center" prop="productName" />
            <el-table-column :show-overflow-tooltip="true" label="商品编码" align="center" prop="productId" />
            <el-table-column label="载体" align="center" prop="carrierType" />
            <el-table-column label="品类" align="center" prop="category" />
            <el-table-column label="自卖/合作" align="center" prop="selfSellingOrCooperation" />
            <el-table-column label="成交金额" align="center" prop="totalAmount" />
            <el-table-column label="成交订单数" align="center" prop="totalOrderCount" />
            <el-table-column label="成交人数" align="center" prop="transactionUsers" />
            <el-table-column label="商品曝光人数" align="center" prop="exposedUsersCount" />
            <el-table-column label="商品点击人数" align="center" prop="productClickPeopleCount" />
            <el-table-column label="曝光点击率" align="center" prop="exposureClickRateCount" />
            <el-table-column label="点击支付率" align="center" prop="clickPaymentRateCount" />
            <el-table-column label="上架时间" align="center" prop="uploadTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.uploadTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="逻辑删除" align="center" prop="isDelete" />
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['productStructure:BiDyMarketingPro:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['productStructure:BiDyMarketingPro:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

        <!-- 添加或修改抖音产品营销数据对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="店铺id" prop="shopId">
                    <el-input v-model.trim="form.shopId" placeholder="请输入店铺id" />
                </el-form-item>
                <el-form-item label="统计周期" prop="dataDate">
                    <el-date-picker clearable v-model="form.dataDate" type="date" value-format="yyyy-MM-dd"
                        placeholder="请选择统计周期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="商品名称" prop="productName">
                    <el-input v-model.trim="form.productName" placeholder="请输入商品名称" />
                </el-form-item>
                <el-form-item label="商品编码" prop="productId">
                    <el-input v-model.trim="form.productId" placeholder="请输入商品编码" />
                </el-form-item>
                <el-form-item label="品类" prop="category">
                    <el-input v-model.trim="form.category" placeholder="请输入品类" />
                </el-form-item>
                <el-form-item label="自卖/合作" prop="selfSellingOrCooperation">
                    <el-input v-model.trim="form.selfSellingOrCooperation" placeholder="请输入自卖/合作" />
                </el-form-item>
                <el-form-item label="成交金额" prop="totalAmount">
                    <el-input v-model.trim="form.totalAmount" placeholder="请输入成交金额" />
                </el-form-item>
                <el-form-item label="成交订单数" prop="totalOrderCount">
                    <el-input v-model.trim="form.totalOrderCount" placeholder="请输入成交订单数" />
                </el-form-item>
                <el-form-item label="成交人数" prop="transactionUsers">
                    <el-input v-model.trim="form.transactionUsers" placeholder="请输入成交人数" />
                </el-form-item>
                <el-form-item label="商品曝光人数" prop="exposedUsersCount">
                    <el-input v-model.trim="form.exposedUsersCount" placeholder="请输入商品曝光人数" />
                </el-form-item>
                <el-form-item label="商品点击人数" prop="productClickPeopleCount">
                    <el-input v-model.trim="form.productClickPeopleCount" placeholder="请输入商品点击人数" />
                </el-form-item>
                <el-form-item label="曝光点击率" prop="exposureClickRateCount">
                    <el-input v-model.trim="form.exposureClickRateCount" placeholder="请输入曝光点击率" />
                </el-form-item>
                <el-form-item label="点击支付率" prop="clickPaymentRateCount">
                    <el-input v-model.trim="form.clickPaymentRateCount" placeholder="请输入点击支付率" />
                </el-form-item>
                <el-form-item label="上架时间" prop="uploadTime">
                    <el-date-picker clearable v-model="form.uploadTime" type="date" value-format="yyyy-MM-dd"
                        placeholder="请选择上架时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="逻辑删除" prop="isDelete">
                    <el-input v-model.trim="form.isDelete" placeholder="请输入逻辑删除" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model.trim="form.remark" placeholder="请输入备注" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 添加或修改产品二级信息对话框 :on-change="handleChange"-->
        <el-dialog title="导入" :visible.sync="dialogVisible" width="500px" append-to-body v-if="dialogVisible">
            <!-- 文件上传-->
            <el-form :rules="rules" :model="dataForm" ref="dataForm" label-width="150px" @submit.native.prevent>
                <!-- <el-form-item label="模版下载" prop="file">
                    <el-button size="mini" @click="downLoadFile"> 下载 </el-button>
                </el-form-item> -->
                <el-form-item label="文件：" prop="file">
                    <el-upload class="upload-import" ref="uploadImport" :http-request="httpRequest" action=""
                        :on-remove="handleRemove" :file-list="fileList" :limit="1" :on-change="handleChange"
                        :auto-upload="false" :before-upload="beforeAvatarUpload">
                        <!--
            accept="application/zip,.zip" 设置接收的文件类型-->
                        <el-button v-show="!hasFile" slot="trigger" size="small" type="primary">选取文件</el-button>
                        <!-- <div slot="tip" class="el-upload__tip">
          只能上传zip文件，且不超过10M
        </div> -->
                    </el-upload>
                    <!-- 关闭自动上传-->
                </el-form-item>
                <el-form-item label="店铺：" prop="name">
                    <!-- <el-input
            type="text"
            v-model.trim="dataForm.name"
            clearable
          ></el-input> -->
                    <el-cascader class="cascader-limited-scroll" v-model="dataForm.name" placeholder="选择店铺分组"
                        :options="cascadeList" :props="{ checkStrictly: true }" style="width: 300px; height: 30px"
                        @change="changecascadeList">
                    </el-cascader>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitUpload">提交</el-button>
                    <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
                    <el-button @click="dialogVisible = false">取 消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import { listBiDyMarketingPro, getBiDyMarketingPro, delBiDyMarketingPro, addBiDyMarketingPro, updateBiDyMarketingPro } from "@/api/productStructure/BiDyMarketingPro";
import { listAll, importBiKeyword } from "@/api/chart/brandChannelShop";
import axios from "axios";
//--------导入token
import { getToken } from "@/utils/auth";
export default {
    name: "BiDyMarketingPro",
    data() {
        return {
            cascadeList: [],
            dataForm: {
                name: [],
                file: null,
            },
            hasFile: false,
            fileList: [],
            dialogVisible: false,
            pjtUrl: process.env.VUE_APP_BASE_API,

            isOpen: false,
            inputValue: '',
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 抖音产品营销数据表格数据
            BiDyMarketingProList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                shopId: null,
                dataDate: null,
                productName: null,
                productId: null,
                carrierType: null,
                category: null,
                selfSellingOrCooperation: null,
                totalAmount: null,
                totalOrderCount: null,
                transactionUsers: null,
                exposedUsersCount: null,
                productClickPeopleCount: null,
                exposureClickRateCount: null,
                clickPaymentRateCount: null,
                uploadTime: null,
                isDelete: null,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
            }
        };
    },
    created() {
        this.getList();
        this.getdataSourceList();
    },
    methods: {
        //搜索栏展示与收起
        shouqi() {
            // console.log(1);
            this.isOpen = !this.isOpen;
        },
        /** 查询抖音产品营销数据列表 */
        getList() {
            this.loading = true;
            listBiDyMarketingPro(this.queryParams).then(response => {
                this.BiDyMarketingProList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                shopId: null,
                dataDate: null,
                productName: null,
                productId: null,
                carrierType: null,
                category: null,
                selfSellingOrCooperation: null,
                totalAmount: null,
                totalOrderCount: null,
                transactionUsers: null,
                exposedUsersCount: null,
                productClickPeopleCount: null,
                exposureClickRateCount: null,
                clickPaymentRateCount: null,
                uploadTime: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                isDelete: null,
                remark: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加抖音产品营销数据";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids
            getBiDyMarketingPro(id).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "修改抖音产品营销数据";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updateBiDyMarketingPro(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addBiDyMarketingPro(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除抖音产品营销数据编号为"' + ids + '"的数据项？').then(function () {
                return delBiDyMarketingPro(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('productStructure/BiDyMarketingPro/export', {
                ...this.queryParams
            }, `BiDyMarketingPro_${new Date().getTime()}.xlsx`)
        },
        //图片上传前的相关判断
        beforeAvatarUpload(file) {
            // const isJPG = file.type == 'image/jpeg' || file.type == 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 100;
            // if (!isJPG) {
            //     this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
            // }
            if (!isLt2M) {
                this.$message.error("上传导入文件大小不能超过 100MB!");
            }

            return isLt2M;
        },
        handleRemove(file, fileList) {
            if (!fileList.length) {
                this.hasFile = false;
            }
            this.dataForm.file = null;
        },
        handleChange(file, fileList) {
            if (fileList.length >= 2) {
                return;
            }
            if (fileList.length === 1) {
                this.hasFile = true;
            }
            this.dataForm.file = file;
        },
        //确定按钮
        //调用组件upload的submit方法，从而触发httpRequest方法，实现手动上传
        submitUpload() {
            this.$refs["dataForm"].validate((valid) => {
                if (valid) {
                    this.$refs.uploadImport.submit();
                }
            });
        },
        httpRequest(param) {
            if (this.dataForm.name.length < 3) {
                this.$modal.msgWarning("请选择到店铺");
                return;
            }
            let fd = new FormData();
            fd.append("file", param.file); // 传文件
            // fd.append("salesGrade", this.dataForm.name);
            // fd.append("brand", this.dataForm.name[0]);
            // fd.append("channel", this.dataForm.name[1]);
            //dataPar.file.raw
            console.log(JSON.stringify(fd));
            this.openLoading();
            axios
                .post(
                    process.env.VUE_APP_BASE_API + "/productStructure/BiDyMarketingPro/importData?salesGrade=" + this.dataForm.name,
                    fd,
                    {
                        headers: {
                            header: { responseType: "blob" },

                            Authorization: "Bearer " + getToken(),
                            "Content-Type": "multipart/form-data",
                        }, //定义内容格式,很重要
                        // timeout: 20000,
                    }
                )
                .then((response) => {
                    this.$modal.closeLoading();
                    console.log(response);
                    if (response.data.code == 200) {
                        this.dialogVisible = false;

                        this.$modal.msgSuccess("导入成功");
                        this.hasFile = false;
                        this.getList();
                    } else {
                        this.$modal.msgError("导入失败");
                    }
                });
        },
        changecascadeList(value) {
            console.log(JSON.stringify(value));
        },
        //部门文件导入修改打开
        daoru() {
            this.dialogVisible = true;
        },
        // 打开加载层
        openLoading() {
            this.$modal.loading("正在导入，请稍候！");
        },
        /** 查询品牌渠道店铺关系列表 */
        getdataSourceList() {
            listAll().then((response) => {
                // let list = [];
                // response.forEach((item) => {
                //   if (item.isTalentLive == "是") {
                //     list.push(item);
                //   }
                // });
                let result = this.transformData(response);
                this.cascadeList = result;
                this.dataForm.name = [
                    result[0].label,
                    result[0].children[0].label,
                    result[0].children[0].children[0].label,
                ];
            });
        },

        //店铺渠道品牌转换

        transformData(data) {
            let result = [];

            data.forEach((item) => {
                let brand = item.brand;
                let channel = item.channel;
                let shopName = item.shopName;

                // 如果brand在结果数组中不存在，则创建一个新的数组
                let brandIndex = result.findIndex(
                    (brandObj) => brandObj.label === brand
                );
                if (brandIndex === -1) {
                    result.push({
                        label: brand,
                        value: brand,
                        children: [],
                        disabled: true,
                    });
                    brandIndex = result.length - 1;
                }

                // 如果channel在当前brand的children数组中不存在，则创建一个新的数组
                let channelIndex = result[brandIndex].children.findIndex(
                    (channelObj) => channelObj.label === channel
                );
                if (channelIndex === -1) {
                    result[brandIndex].children.push({
                        label: channel,
                        value: channel,
                        children: [],
                        disabled: true,
                    });
                    channelIndex = result[brandIndex].children.length - 1;
                }

                // 如果shopName在当前channel的children数组中不存在，则创建一个新的数组
                let shopIndex = result[brandIndex].children[
                    channelIndex
                ].children.findIndex((shopObj) => shopObj.label === shopName);
                if (shopIndex === -1) {
                    result[brandIndex].children[channelIndex].children.push({
                        label: shopName,
                        value: shopName,
                        // children: []
                    });
                }
            });

            return result;
        },
    }
};
</script>
